package com.rfsp.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.common.service.ParamService;
import com.rfsp.common.service.UserService;

@Component
public class SessionInterceptor implements HandlerInterceptor {

	public Logger log = LoggerFactory.getLogger(SessionInterceptor.class);
	
	@Autowired
	UserService userService;
	
	@Autowired
	ParamService paramService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("SessionInterceptor: uri={}", request.getRequestURI());
//		HttpSession session = request.getSession();
		UserPO user = ShiroUtils.getAttribute("user");
		
		String LoginType = ShiroUtils.getAttribute("login_type");
		if("0".equals(LoginType)) {
			return true;
		} else if("1".equals(LoginType)) {
			if(user!=null && StringUtils.isNoneEmpty(user.getUserCode())) {
				log.error("session ID----------1111111111111111111111111111");
				String sessionId = userService.getUserSession(user.getUserCode());
				Object objSession = ShiroUtils.getAttribute("sessionId");
				if(StringUtils.equals(sessionId, objSession.toString())) {
					return true;
				}
			}
		}
		WebUtils.issueRedirect(request, response, "/error/notLogin", null, true, false);
//		String domain = paramService.getValue("OUT_URL_HTTP") + "/mcp";
//		String err = domain + "/error/notLogin";
//		response.sendRedirect(err);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
